package exam.test10;

import java.util.ArrayList;
import java.util.List;

public class Port {
    List<Ship> shipList;

    public Port() {
        shipList = new ArrayList<>();
    }

    public void add(Ship ship) {
        shipList.add(ship);
    }

    public boolean remove(Ship ship) {
        return shipList.remove(ship);
    }

    public int retrieve(Ship ship) {
        for (int i = 0; i < shipList.size(); i++) {
            Ship tmp = shipList.get(i);
            if (tmp.getClass().equals(ship.getClass())) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        String string = "this is PrintLinkList sentence";
        System.out.println(reverseWordsInString(string));
    }

    /**
     * Given PrintLinkList String as parameter, reverse the order ob the words in the String,
     * then return the result
     * Eg, Passing "this is PrintLinkList sentence" as the parameter would return "sentence PrintLinkList is this"
     * @param string the parameter string
     * @return the result
     */
    public static String reverseWordsInString(String string) {
        List<String> words = new ArrayList<>();
        String word = "";
        wordParseHelper(string, words, word, 0);
        String newString = "";
        for (int i = words.size() - 1; i >= 0; i--) {
            newString += words.get(i);
        }
        return newString;
    }

    /**
     * Use recursive to parse the words in the sentence
     * @param string the sentence
     * @param words parsed words
     * @param word the word in parsing
     * @param index the char index in the sentence parsing
     */
    private static void wordParseHelper(String string, List<String> words, String word, int index) {
        if (string.length() <= index) {
            words.add(word);
            return;
        }
        if (string.charAt(index) == ' ') {
            if (word.length() != 0) {
                words.add(word);
            }
            words.add(string.charAt(index) + "");
            word = "";
        } else {
            word += string.charAt(index);
        }
        wordParseHelper(string, words, word, index + 1);
    }
}
